var dealerNawSavedSearch = 'customsearch_at_dealer_xml_naw';

var dealerAddressSavedSearch = 'customsearch_at_dealer_xml_address';
var dealerBrandsSavedSearch = 'customsearch_at_dealer_xml_brands';
var dealerContactsSavedSearch = 'customsearch_at_dealer_xml_contacts';
var dealerMembershipsSavedSearch = 'customsearch_at_dealer_xml_memberships';
var dealerWebsiteGroupsSavedSearch = 'customsearch_at_dealer_xml_website_group';

var dealerStockSavedSearch = 'customsearch_at_dealer_xml_stock';
var dealerKitProductsSavedSearch = 'customsearch_at_dealer_xml_kit_products';
var dealerItemProductsSavedSearch = 'customsearch_at_dealer_xml_item_products';

var dealerActiveContractsSavedSearch = 'customsearch_at_dealer_xml_active_contra';

var xmlFolderId = nlapiSearchRecord('folder', null, new nlobjSearchFilter('name', null, 'is', 'Dealer XML'), null)[0].getId();
var logFolderId = nlapiSearchRecord('folder', null, new nlobjSearchFilter('name', null, 'is', 'Dealer XML Logs'), null)[0].getId();

var xmlPostUrl = nlapiGetContext().getSetting('script', 'custscript_at_xml_post_url');
var xmlPostHeaders = {
    'Content-Type': 'application/xml'
};

var postToFloris = true;
var florisPostUrl = 'http://www.123hostme.nl/AutoTraderWebServices.svc/SynchronizeDealers/10';

function beforeSubmit(type){
    var customer = nlapiGetNewRecord();
    var activeField = customer.getFieldValue('custentity_at_active');
    
    var contracts = nlapiSearchRecord('transaction', dealerActiveContractsSavedSearch, new nlobjSearchFilter('entityid', 'customer', 'is', customer.getFieldValue('entityid')), null);
    var active = (contracts != null && contracts.length > 0) ? 'T' : 'F';
    
    if (activeField != active) {
        customer.setFieldValue('custentity_at_active', active);
    }
}

function afterSubmit(type){
    var customers = nlapiSearchRecord('customer', dealerNawSavedSearch, new nlobjSearchFilter('internalid', null, 'is', nlapiGetRecordId()));
    
    if (customers != null && customers.length > 0) {
        var customer = customers[0];
        var dealerId = customer.getValue('entityid');
        
        nlapiLogExecution('debug', 'Dealer id: ' + dealerId, 'XML sync started');
        
        var dealer = getDealerData(customer);
        var dealerXML = createXML(dealer);
        
        var xmlFile = nlapiCreateFile('dealer_xml_' + dealerId + '.xml', 'XMLDOC', dealerXML);
        xmlFile.setFolder(xmlFolderId);
        xmlFile.setIsOnline(true);
				xmlFile.setEncoding('UTF-8');
        nlapiSubmitFile(xmlFile);
        
        try {
            var responseXML = nlapiRequestURL(xmlPostUrl, xmlFile.getValue(), xmlPostHeaders).getBody();
            
            var logFile = nlapiCreateFile('dealer_xml_log_' + dealerId + '.xml', 'XMLDOC', responseXML);
            logFile.setFolder(logFolderId);
            logFile.setIsOnline(true);
            nlapiSubmitFile(logFile);
            if (responseXML.indexOf('Error') != -1) {
                nlapiLogExecution('error', 'Dealer id: ' + dealerId + 'POST Failed', responseXML);
            }
        } 
        catch (e) {
            nlapiLogExecution('error', 'Dealer id: ' + dealerId + 'POST Failed', e.message);
        }
        
        //Post to Floris
        if (postToFloris) {
            try {
                var florisResponse = nlapiRequestURL(florisPostUrl, dealerXML, xmlPostHeaders).getBody();
            } 
            catch (e) {
                nlapiLogExecution('error', 'Dealer id: ' + dealerId + 'Floris POST Failed', e.message);
            }
        }
        
        nlapiLogExecution('debug', 'Dealer id: ' + dealerId, 'XML sync completed');
    }
}

function getDealerData(customer){
    var dealerId = customer.getValue('entityid');
    var parentId = customer.getValue('entityid', 'parentCustomer');
    
    return {
        id: dealerId,
        companyname: xmlEncode(customer.getValue('companyname')),
        parentid: parentId != '' ? parentId : dealerId,
        contacts: getDealerContacts(dealerId),
        address: getDealerAddress(dealerId),
        phone: customer.getValue('custentity_phone_website') != '' ? customer.getValue('custentity_phone_website') : customer.getValue('phone'),
        mobile: customer.getValue('custentity_mobile_website'),
        fax: customer.getValue('custentity_fax_website') != '' ? customer.getValue('custentity_fax_website') : customer.getValue('fax'),
        email: customer.getValue('custentity_at_email_website') != '' ? customer.getValue('custentity_at_email_website') : customer.getValue('email'),
        website: customer.getValue('custentity_at_website_website') != '' ? customer.getValue('custentity_at_website_website') : customer.getValue('url'),
        groepwebsite: customer.getValue('custentity_at_groepwebsite'),
        datafeedprovider: customer.getText('custentity_vendor'),
        stock: getDealerStock(dealerId),
        type: customer.getText('custrecord_type_bedrijf', 'custentity_company_type'),
        status: customer.getValue('custentity_at_active') == 'T' ? 'actief' : 'inactief',
        ismerkdealer: customer.getValue('custrecord_merkdealer', 'custentity_company_type') == 'T' ? 'ja' : 'nee',
        brands: getDealerBrands(dealerId),
        isnapmember: getDealerIsNapMember(dealerId),
        napnumber: customer.getValue('custentity_nap_nummer'),
        isbovagmember: getDealerIsBovagMember(dealerId),
        memberships: getDealerMemberships(dealerId),
        paymentmethod: customer.getText('terms') == 'Z007' ? 'automatische incasso' : 'op rekening',
        products: getDealerProducts(customer, dealerId),
        websitegroups: getDealerWebsiteGroups(dealerId)
    }
}

function getDealerAddress(dealerId){
    var address = null;
    var customers = nlapiSearchRecord('customer', dealerAddressSavedSearch, new nlobjSearchFilter('entityid', null, 'is', dealerId), null);
    
    if (customers != null && customers.length > 0) {
        address = {
            street: xmlEncode(customers[0].getValue('address1')),
            number: customers[0].getValue('address2'),
            zip: customers[0].getValue('zipcode'),
            city: customers[0].getValue('city'),
            country: customers[0].getValue('country')
        }
    }
    
    return address;
}

function getDealerBrands(dealerId){
    var brands = new Array();
    var customers = nlapiSearchRecord('customer', dealerBrandsSavedSearch, new nlobjSearchFilter('entityid', null, 'is', dealerId), null);
    if (customers != null && customers.length > 0) {
        for (var i = 0; i < customers.length; i++) {
            brands.push(customers[i].getValue('name', 'custentity_brands'));
        }
    }
    return brands;
}

function getDealerContacts(dealerId){
    var contacts = new Array();
    var customers = nlapiSearchRecord('customer', dealerContactsSavedSearch, new nlobjSearchFilter('entityid', null, 'is', dealerId), null);
    if (customers != null && customers.length > 0) {
        for (var i = 0; i < customers.length; i++) {
            contacts.push(customers[i].getValue('formulatext'));
        }
    }
    return contacts;
}

function getDealerIsNapMember(dealerId){
    var filters = new Array();
    filters[0] = new nlobjSearchFilter('entityid', null, 'is', dealerId);
    filters[1] = new nlobjSearchFilter('custrecord_membership_is_nap', 'custentity_at_memberships', 'is', 'T');
    var customers = nlapiSearchRecord('customer', dealerMembershipsSavedSearch, filters, null);
    return (customers != null && customers.length > 0) ? 'ja' : 'nee';
}

function getDealerIsBovagMember(dealerId){
    var filters = new Array();
    filters[0] = new nlobjSearchFilter('entityid', null, 'is', dealerId);
    filters[1] = new nlobjSearchFilter('custrecord_membership_is_bovag', 'custentity_at_memberships', 'is', 'T');
    var customers = nlapiSearchRecord('customer', dealerMembershipsSavedSearch, filters, null);
    return (customers != null && customers.length > 0) ? 'ja' : 'nee';
}

function getDealerMemberships(dealerId){
    var memberships = new Array();
    var customers = nlapiSearchRecord('customer', dealerMembershipsSavedSearch, new nlobjSearchFilter('entityid', null, 'is', dealerId), null);
    if (customers != null && customers.length > 0) {
        for (var i = 0; i < customers.length; i++) {
            var isInternetLabel = customers[i].getValue('custrecord_at_internetlabel', 'custentity_at_memberships');
            if (isInternetLabel == 'T') {
                memberships.push(customers[i].getValue('name', 'custentity_at_memberships'));
            }
        }
    }
    return memberships;
}

function getDealerProducts(customer, dealerId){
    var products = new Array();
    if (customer.getValue('custentity_export_email_to_website') == 'T') {
        products.push('weergeven emailadres');
    }
    //Kit Products
    var customers = nlapiSearchRecord('transaction', dealerKitProductsSavedSearch, new nlobjSearchFilter('entityid', 'customer', 'is', dealerId), null);
    if (customers != null && customers.length > 0) {
        for (var i = 0; i < customers.length; i++) {
            var productXmlName = getProductXmlName(customers[i].getText('memberitem', 'item'));
            if (productXmlName != '') {
                products.push(productXmlName);
            }
        }
    }
    //Item Products
    var customers = nlapiSearchRecord('transaction', dealerItemProductsSavedSearch, new nlobjSearchFilter('entityid', 'customer', 'is', dealerId), null);
    if (customers != null && customers.length > 0) {
        for (var i = 0; i < customers.length; i++) {
            var productXmlName = getProductXmlName(customers[i].getText('item'));
            if (productXmlName != '') {
                products.push(productXmlName);
            }
        }
    }
    
    return products;
}

function getDealerStock(dealerId){
    var stock = '';
    var customers = nlapiSearchRecord('transaction', dealerStockSavedSearch, new nlobjSearchFilter('entityid', 'customer', 'is', dealerId), null);
    if (customers != null && customers.length > 0) {
        for (var i = 0; i < customers.length; i++) {
            stock = customers[i].getValue('memberquantity', 'item');
        }
    }
    return stock;
}

function getDealerWebsiteGroups(dealerId){
    var websitegroups = new Array();
    var customers = nlapiSearchRecord('customer', dealerWebsiteGroupsSavedSearch, new nlobjSearchFilter('entityid', null, 'is', dealerId), null);
    if (customers != null && customers.length > 0) {
        for (var i = 0; i < customers.length; i++) {
            websitegroups.push(customers[i].getValue('name', 'custentity_at_website_groups'));
        }
    }
    return websitegroups;
}

function createXML(dealer){
    var output = '<?xml version="1.0" encoding="UTF-8"?>';
    output += '<enveloppe username="AllSolutions" senderMessageID="UUID" xsi:noNamespaceSchemaLocation="AutoTraderWSEnvelopInboundFull10.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
    output += '<SynchronizeDealers>';
    output += '<Dealer>';
    output += '<DID>' + dealer.id + '</DID>';
          nlapiLogExecution('debug', 'companyname', dealer.companyname);
    output += '<CompanyName>' + dealer.companyname + '</CompanyName>';
    if (dealer.parentid != '') {
        output += '<HoldingDID>' + dealer.parentid + '</HoldingDID>';
    }
    if (dealer.contacts.length > 0) {
        output += '<Contacts>';
        for (var contact in dealer.contacts) {
            output += '<NameContact>' + dealer.contacts[contact] + '</NameContact>';
        }
        output += '</Contacts>';
    }
    if (dealer.address != null) {
        var address = dealer.address;
        if (address.street != '') {
            output += '<Address>' + address.street + '</Address>';
        }
        if (address.number != '') {
            output += '<AddressNumber>' + address.number + '</AddressNumber>';
        }
        if (address.zip != '') {
            output += '<Postcode>' + address.zip + '</Postcode>';
        }
        if (address.city != '') {
            output += '<City>' + address.city + '</City>';
        }
        if (address.country != '') {
            output += '<Country>' + address.country + '</Country>';
        }
    }
    if (dealer.phone != '') {
        output += '<Phone1>' + dealer.phone + '</Phone1>';
    }
    if (dealer.mobile != '') {
        output += '<Phone2>' + dealer.mobile + '</Phone2>';
    }
    if (dealer.fax != '') {
        output += '<Fax>' + dealer.fax + '</Fax>';
    }
    if (dealer.email != '') {
        output += '<Email>' + dealer.email + '</Email>';
    }
    if (dealer.website != '') {
        output += '<Website>' + dealer.website + '</Website>';
    }
    if (dealer.groepwebsite != '') {
        output += '<AutotraderURL>' + dealer.groepwebsite + '</AutotraderURL>';
    }
    if (dealer.datafeedprovider != '') {
        output += '<AdvertProviders>';
        output += '<AdvertProvider>' + dealer.datafeedprovider + '</AdvertProvider>';
        output += '</AdvertProviders>';
    }
    if (dealer.stock != '') {
        output += '<Stock>' + dealer.stock + '</Stock>';
    }
    output += '<DealerType>' + dealer.type + '</DealerType>';
    output += '<DealerStatus>' + dealer.status + '</DealerStatus>';
    output += '<NAPmember>' + dealer.isnapmember + '</NAPmember>';
    if (dealer.napnumber != 0) {
        output += '<RDCNumber>' + dealer.napnumber + '</RDCNumber>';
    }
    output += '<MakeDealer>';
    output += '  <IsMakeDealer>' + dealer.ismerkdealer + '</IsMakeDealer>';
    if (dealer.brands.length > 0) {
        output += '  <Makes>';
        for (var brand in dealer.brands) {
            output += '<Make>' + dealer.brands[brand] + '</Make>'
        }
        output += '  </Makes>';
    }
    output += '</MakeDealer>';
    output += '<BOVAGMemberships>';
    output += '  <IsBOVAGMember>' + dealer.isbovagmember + '</IsBOVAGMember>';
    if (dealer.memberships.length > 0) {
        output += '  <Memberships>';
        for (var membership in dealer.memberships) {
            output += '<Membership>' + dealer.memberships[membership] + '</Membership>'
        }
        output += '  </Memberships>';
    }
    output += '</BOVAGMemberships>';
    if (dealer.websitegroups.length > 0) {
        output += '  <DealerGroups>';
        for (var websitegroup in dealer.websitegroups) {
            output += '<DealerGroupId>' + dealer.websitegroups[websitegroup] + '</DealerGroupId>'
        }
        output += '  </DealerGroups>';
    }
    if (dealer.products.length > 0) {
        output += '<AdvertProducts>';
        for (var product in dealer.products) {
            output += '<Product>' + dealer.products[product] + '</Product>';
        }
        output += '</AdvertProducts>';
    }
    output += '<PaymentMethod>' + dealer.paymentmethod + '</PaymentMethod>';
    output += '</Dealer>';
    output += '</SynchronizeDealers>';
    output += '</enveloppe>';
    return output;
}

function getProductXmlName(productname){
    if (productname == 'Link') {
        return 'link naar website';
    }
    if (productname == 'Optional Items : PromWeergave') {
        return 'prominente weergave';
    }
    if (productname == 'Optional Items : Bedrijfsvoorraad') {
        return 'voorraad';
    }
    if (productname == 'Optional Items : VoorraadLijst') {
        return 'voorraadpagina';
    }
    if (productname == 'Optional Items : WebsiteHosting') {
        return 'hosting';
    }
    return '';
}

function xmlEncode(string){
    return string.replace(/\&/g, '&' + 'amp;').replace(/</g, '&' + 'lt;').replace(/>/g, '&' + 'gt;').replace(/\'/g, '&' + 'apos;').replace(/\"/g, '&' + 'quot;');
}
